/**
 * __router__:
 * 服务器端的中央控制器
 *
 * User: ZhangXiao
 * Date: 14-4-23
 * Time: 下午5:30
 * File: sys/__router__.js
 */

var url = require("url");
var path = require("path");
var util = require("util");
var tools = require("./tools");
var mime = require("./mime").mime;
var static = require("./static").static;
var dynamic = require("./dynamic").dynamic;

/**
 * __handlers__:键值对中的键相当于请求中的pathname, http://localhost:8088/pathnam?query=v
 *
 * __handlers__={"pathname1":function,"pathname2":function};
 *
 */

var _options = {};

//缓存对象
var _handlers = {};

/**
 *服务器的中央控制程序，用来处理请求控制，转发，响应
 *
 * @param request
 * @param response
 * @param options
 */
function router(request, response, options) {

    _options = tools.copyObject(options);

    _handlers = _options.handlers;

    var location = url.parse(request.url);

    if (location.path === "" || location.path === "/" || location.path === "/index") {
        staticRouter(_options.client.home, request, response, _options);
    } else {
        var ext = path.extname(location.pathname);
        if (ext !== "" && ext != ".") {
            if (mime.isExistType(ext.slice(1))) {
                staticRouter(location.pathname, request, response, _options);
            } else {
                _handlers["handler_404"](request, response, _options);
            }
        } else {
            dynamicRouter(location.pathname, request, response, _options);
        }
    }
}


function staticRouter(pathname, request, response, options) {
    static(pathname, request, response, options);
}

function dynamicRouter(pathname, request, response, options) {
    dynamic(pathname, request, response, options);
}

exports.router = router;
